import axios from 'axios';
import router from '../router';
import qs from 'qs';
const validateStatus = (status) => {
    return status >= 200 && status < 300;
};
axios.defaults.timeout = 6000;
axios.defaults.withCredentials = true; // 设置允许跨域设置cookie
// 开发环境下给定，生产环境删除
//axios.defaults.baseURL='/apis'
//axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '' : '/apis';
axios.defaults.baseURL = 'http://192.168.6.11:9010'
axios.defaults.validateStatus = validateStatus;
axios.defaults.headers['Content-Type'] = 'application/json';
axios.defaults.headers['x-requested-with'] = 'XMLHttpRequest';
let cancel;
const promiseArr = {};
// http request 拦截器
axios.interceptors.request.use(
    (config) => {
        //发起请求时，取消掉当前正在进行的相同请求
        if (promiseArr[config.url]) {
            promiseArr[config.url]('操作取消');
            promiseArr[config.url] = cancel;
        } else {
            promiseArr[config.url] = cancel;
        }
        config.headers.token = localStorage.getItem('TOKEN') || '';
        if (config.headers['Content-Type'] == 'application/x-www-form-urlencoded') {
            config.data = qs.stringify(config.data);
        }
        return config;
    },
    (err) => {
        return Promise.reject(err);
    }
);

// http request 拦截器
axios.interceptors.response.use(
    (resp) => {
        console.log(resp)
        const { code, msg } = resp.data;
        if (code == '401') { //登陆超时重新登陆
            router.push('/login');
            localStorage.clear()
            return Promise.reject(msg);
        }
        if (code == '402') { //token过期重新获取token调用之前的方法 
            router.push('/login');
            localStorage.clear()
            return Promise.reject(msg);
            // return axios.get('/apis'+'/system/token/refresh' + "?refreshToken=" + localStorage.getItem("refreshToken"))
            //     .then((res) => {
            //         localStorage.setItem("TOKEN", res.data.data)
            //         return axios.request(resp.config).then((resps) => {
            //             return resps
            //         }).catch((err)=>{        
            //           router.push('/login');
            //           return Promise.reject(err.msg);
            //         })                   
            //     })
        }
        if (code == '500') {
            return Promise.reject('系统异常')
        }
        if (!validateStatus(code) && code !== undefined) { //返回错误状态
            return Promise.reject(msg);
        }
        return resp;
    },
    (err) => {
        console.log(err)
        if (err.response.status === 401) {
            router.push('/login');
        }
        return Promise.reject(err);
    }
);

export default axios;
